/**
 * 三维面积测量
 * @author wangxd
 */

import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { jsapi, viewUtils } from '@/utils/arcgis/index';
import { ConnectProps, ConnectState } from '@/models/connect';
import { MaptoolbarModelState } from '@/models/maptoolbar';

// 默认样式
const _color = 'rgba(255, 255, 255, 0.4)';
const _colorBackground = 'transparent';
const _colorHintText = 'rgba(255, 255, 255, 0.5)';
const _colorButton = '#2FB0FF';
const _colorButtonHover = '#ffffff';
const _colorSelectBackground = '#2FB0FF';

interface MapToolbarPropTypes extends ConnectProps {
  // maptoolbar: MaptoolbarModelState;
  /** 包裹的外部div样式 */
  style?: React.StyleHTMLAttributes<HTMLDivElement>;
  /** 测量数据与选择框字体颜色 */
  color?: string;
  /** 选择框背景颜色，包含下拉框 */
  colorSelectBackground?: string;
  /** 鼠标悬浮button字体颜色 */
  colorButtonHover?: string;
  /** button字体与border颜色，以及鼠标悬浮后背景色 */
  colorButton?: string;
  /** 操作提示字体颜色 */
  colorHintText?: string;
  /** 整体背景颜色 */
  colorBackground?: string;
  /** 取消所有组件赋予的样式 */
  noCustomStyle?: boolean;
}

const DIV_CLS = 'geomap-widget__area-measurement-3d';
const _DIV_CLS = '.' + DIV_CLS;

const MeasureArea3D: React.FC<MapToolbarPropTypes> = props => {
  const domRef: React.RefObject<HTMLInputElement> = useRef<any>(null);
  const [loading, setLoading] = useState(true);
  const measrueArea = useRef<any>();
  const {
    color = _color,
    colorBackground = _colorBackground,
    colorHintText = _colorHintText,
    colorButton = _colorButton,
    colorButtonHover = _colorButtonHover,
    colorSelectBackground = _colorSelectBackground,
    noCustomStyle = false,
  } = props;

  // 样式模板，根据组件传入的样式生成样式挂载在头部
  const cssInnerHtml = `
    /* 测量微件颜色 */
     ${_DIV_CLS} {}
   
     ${_DIV_CLS} .esri-widget {
       background: ${colorBackground};
     }
     ${_DIV_CLS} .esri-button {
       color: ${colorButton};
       border: 1px solid ${colorButton};
     }
     ${_DIV_CLS} .esri-area-measurement-3d__hint-text{
       color: ${colorHintText};
     }
   
     ${_DIV_CLS} .esri-area-measurement-3d__measurement {
       background: ${colorBackground};
       color: ${color} ;
     }
   
   
   
     ${_DIV_CLS} .esri-button:hover {
       background-color: ${colorButton} ;
       border: 1px solid ${colorButton} ;
       color: ${colorButtonHover} ;
     }
   
     ${_DIV_CLS} .esri-area-measurement-3d__units-label {
       color: ${color} ;
     }
   
     ${_DIV_CLS} .esri-area-measurement-3d__units-select-wrapper  .esri-select {
       background-color: ${colorSelectBackground}  ;
       color: ${color} ;
     }
   `;

  useEffect(() => {
    if (document.getElementById('area-measurement-3d') || noCustomStyle) return;
    // 初始化组件时挂载样式
    const head = document.head || document.getElementsByTagName('head')[0];
    const style = document.createElement('style');
    head.appendChild(style);
    style.type = 'text/css';
    style.id = 'area-measurement-3d';
    style.innerHTML = cssInnerHtml;
  }, []);

  useEffect(() => {
    creatWidget(window.agsGlobal.view);
    return () => {
      // 组件卸载时需要将组件destroy
      measrueArea.current && measrueArea.current.destroy();
    };
    async function creatWidget(view) {
      const newDiv = document.createElement('div');
      const [AreaMeasurement3D] = await jsapi.load(['esri/widgets/AreaMeasurement3D']);
      measrueArea.current = new AreaMeasurement3D({
        view: view,
        container: newDiv,
      });
      setLoading(false);
      if (domRef.current) {
        domRef.current.appendChild(newDiv);
      }
      changeAreaUnit(view);
    }
  }, []);

  /**
   * 修改测量微件默认单位
   */
  function changeAreaUnit(view) {
    const interval4areaMeasureUnit = setInterval(() => {
      if (view.activeTool) {
        // console.log(view.activeTool)
        view.activeTool.unit = 'square-meters';
        clearInterval(interval4areaMeasureUnit);
      }
    }, 10);
    const interval4areaMeasurePanel = setInterval(() => {
      if (document.getElementsByClassName('esri-area-measurement-3d__units-select esri-select')) {
        if (
          document.getElementsByClassName('esri-area-measurement-3d__units-select esri-select')
            .length > 0
        ) {
          clearInterval(interval4areaMeasurePanel);
          const dom = document.getElementsByClassName(
            'esri-area-measurement-3d__units-select esri-select',
          );
          const ops: any = dom[0];
          if (ops) {
            if (ops.length > 0) {
              for (let i = 0; i < ops.length; i += 1) {
                const tempValue = ops[i].value;
                if (tempValue === 'square-meters') {
                  ops[i].selected = true;
                }
              }
            }
          }
        }
      }
    }, 10);
  }

  return (
    <div className={DIV_CLS}>
      <div ref={domRef} />
      {loading && (
        <div
          style={{
            textAlign: 'center',
            padding: '30px 50px',
            margin: '20px 0',
          }}
        >
          <Spin
            size="large"
            spinning={loading}
            indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
          />
        </div>
      )}
    </div>
  );
};

// export default connect(({ maptoolbar }: ConnectState) => {
//   return {
//     maptoolbar,
//   };
// })(MeasureArea3D);
export default MeasureArea3D;
